package com.codeman.crawl.core.schedule;


import com.codeman.business.crawl.domain.CrawlSource;
import com.codeman.common.constant.Constants;
import com.codeman.common.core.redis.RedisCache;
import com.codeman.common.utils.ThreadUtils;
import com.codeman.crawl.service.ICrawlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 爬虫线程监控器,监控执行完成的爬虫源，并修改状态
 *
 * @author Administrator
 */
@Service
@Slf4j
public class CrawlThreadMonitor {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ICrawlService crawlService;

    @Scheduled(fixedRate = 1000 * 60 * 5)
    public void monitor() {

        //查询需要监控的正在运行的爬虫源
        List<CrawlSource> sources = crawlService.queryCrawlSourceByStatus("1");

        for (CrawlSource source : sources) {
            Set<Long> runningCrawlThreadIds = redisCache.getCacheObject(Constants.RUNNING_CRAWL_THREAD_KEY_PREFIX + source.getId());
            boolean sourceStop = true;
            if (runningCrawlThreadIds != null) {
                for (Long threadId : runningCrawlThreadIds) {
                    Thread thread = ThreadUtils.findThread(threadId);

                    if (thread != null && thread.isAlive()) {
                        //有活跃线程，说明该爬虫源正在运行，数据库中状态正确，不需要修改
                        sourceStop = false;

                    }

                }
            }

            if (sourceStop) {
                crawlService.updateCrawlSourceStatus(source.getId(), "0");
            }


        }

    }
}
